package stone926.mods.more_enchantments.enchantments.creative;

import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.FallingBlockEntity;
import net.minecraft.particle.ParticleTypes;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import stone926.mods.more_enchantments.mixins.accessors.FallingBlockEntityAccessor;

import java.util.Random;

public class FallingBlockCreatorEnchantment extends AbstractCreativeOnlyEnchantment {

  public static Pair<BlockState, BlockPos> createFallingBlock(World world, BlockPos pos) {
    if (!world.getBlockState(pos).isOf(Blocks.AIR)) {
      int YPos = pos.getY() + 10 + new Random().nextInt(15);
      if (world instanceof ServerWorld server) {
        FallingBlockEntity fallingBlock = new FallingBlockEntity(EntityType.FALLING_BLOCK, server);
        fallingBlock.setPosition(pos.getX() + 0.5, YPos, pos.getZ() + 0.5);
        ((FallingBlockEntityAccessor) fallingBlock).setBlockState(world.getBlockState(pos));
        fallingBlock.setHurtEntities(10, Integer.MAX_VALUE);
        fallingBlock.dropItem = true;
        fallingBlock.timeFalling = -1000;
        server.spawnEntity(fallingBlock);
        server.breakBlock(pos, false);
        server.spawnParticles(ParticleTypes.HAPPY_VILLAGER, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, 100, 0.4, 0.4, 0.4, 0);
      }
      return new ImmutablePair<>(world.getBlockState(pos), pos.withY(YPos));
    }
    return new ImmutablePair<>(Blocks.AIR.getDefaultState(), new BlockPos(0, 0, 0));
  }

}
